package pyf.demo11;

/**
 * @author pengyifeng
 * @version 5.1
 * @ClassName ThreadTicketDemo.java
 * @Description 抢票引发的并发问题
 * @createTime 2021年07月27日 10:54:00
 */
public class ThreadTicketDemo {



    static class BuyTicket implements Runnable {
        /**
         * 票
         */
        private Integer num = 10;
        private boolean  flag = true;

        @Override
        public void run() {
            while (flag){
                buy();
            }

        }

        private synchronized void buy() {
            //判断是否邮票
            if(num<0){
                flag=false;
                return;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "拿到第" + num-- + "票");
        }
    }

    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket,"黄牛").start();
        new Thread(buyTicket,"小明").start();
        new Thread(buyTicket,"小红").start();
    }
}
